<style scoped>

</style>
<template>
    <div>
        <div class="top-title bg-white">
            <div class="top-title-text black blod" style="font-size:22px;">账号管理</div>
        </div>
        <div class="page-content flex-column bg-white" style="height: calc(100% - 50px);">




            <div class="flex m-b-20" style="height: calc(100% - 50px)">

                <div class="w25p" style="height: calc(100% - 50px)">
                    <div class="top-title-text text-18 black blod">组织机构</div>
                    <div class="m-10 p-15" style="border:1px solid #ccc;" :style="{height: '100%'}">
                        <!--<Input v-model="search.str" class="" type="text" placeholder="请输入机构名称"/>-->

                        <Tree :data="list" :render="renderContent" @on-select-change="changeSelect"></Tree>

                    </div>



                </div>
                <div class="w70p" v-show="detail && detail.id">
                    <div class="top-title-text text-18 black blod">账号信息 - {{detail.or_name}}</div>
                    <div class="search-block bg-white p-10">
                        <Form inline :label-width="90">
                            <FormItem :label-width="0">
                                <Button @click="addItem" class="m-r-10" type="primary"><img src="assets/image/add.png">新增</Button>
                            </FormItem>
                        </Form>
                    </div>
                    <div class="p-10" style="padding-top:0;">

                        <div id="mainContent" class="">

                            <div class="">
                                <Table height="500"
                                       :columns="columns"
                                       :data="userList"
                                >
                                    <template slot-scope="{ row }" slot="status">
                                        <i-switch v-model="row.state" @on-change="changeStatus(row)" />

                                    </template>
                                </Table>
                            </div>

                        </div>
                        <div class="page-box">
                            <Page :total="total"
                                  :current="page"
                                  show-sizer show-elevator show-total
                                  @on-change="onPageChange"
                                  @on-page-size-change="changePageSize"
                                  :page-size="pageSize"
                            />
                        </div>

                    </div>

                </div>
            </div>

        </div>


        <Modal v-model="itemModal"
               :title="itemData.id? '编辑账号': '新增账号'"
               class-name="vertical-center-modal"
               width="800"
        >
            <div class="p-l-20">
                <div class="top-title-text text-18 black blod">基础信息</div>
                <div class="p-15-0 max-h500">
                    <Form label-position="top">

                        <Row>
                            <Col span="11">
                                <FormItem label="所属机构" required>
                                    <Input readonly v-model="detail.or_name" class="w240" type="text" placeholder="请输入"/>
                                </FormItem>
                            </Col>
                            <Col span="2" style="text-align: center"></Col>
                            <Col span="11">
                                <FormItem label="账号" required>
                                    <Input v-model="itemData.user_account" class="w240" type="text" placeholder="请输入"/>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row>
                            <Col span="11">
                                <FormItem label="真用户名称" required>
                                    <Input v-model="itemData.user_name" class="w240" type="text" placeholder="请输入"/>
                                </FormItem>
                            </Col>
                            <Col span="2" style="text-align: center"></Col>
                            <Col span="11">
                                <FormItem label="角色" required>
                                    <Select v-model="itemData.role_id" class="w160"placeholder="请选择" clearable transfer>
                                        <Option v-for="(item,i) in roleList"
                                                :key="i"
                                                :value="item.id"
                                        >{{item.role_name}}</Option>
                                        <Option value="2">业务人员</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>

                    </Form>

                </div>
            </div>

            <div slot="footer">
                <Button @click="itemModal = false" class="m-r-10">取消</Button>
                <Button @click="confirm" type="primary">确定</Button>
            </div>
        </Modal>

    </div>
</template>

<script>

    export default {
        data() {
            return {
                search: {
                    str: '',
                },

                tableHeight: 500,

                detail: {},
                list: [],

                itemModal: false,
                itemData: {
                    "orgnization_id": "",
                    "role_id": "",
                    "role_name": "",
                    "user_account": "",
                    "user_name": ""
                },


                total: 0,
                page: 1,
                pageSize: 10,

                roleList: [],
                userList: [
                    {
                        status: true,
                    }
                ],
                columns: [
                    {
                        title: '名称',
                        key: 'user_name',
                    },
                    {
                        title: '账号',
                        key: 'user_account'
                    },
                    {
                        title: '角色',
                        key: 'role_name'
                    },
                    {
                        title: '所属机构',
                        key: 'orgnizationName'
                    },
                    {
                        title: '状态',
                        key: 'state',
                        slot: 'status',
                    },
                    {
                        title: '操作',
                        width: 190,
                        render: (h, params) => {
                            let look = h('a', {
                                class: 'm-r-10',
                                on: {
                                    click: () => {
                                        console.log('查看', params.row);
                                        this.$router.push({
                                            path: `/iotManage/doorDetail?type=${this.type}&id=${params.row.id}`
                                        })
                                    }
                                }
                            }, '查看');
                            let edit = h('a', {
                                class: 'm-r-10',
                                on: {
                                    click: () => {
                                        console.log('编辑', params.row);
                                        this.editItem(params.row);
                                    }
                                }
                            }, '编辑');
                            let del = h('a', {
                                class: 'red m-r-10',
                                on: {
                                    click: () => {
                                        console.log('删除', params.row);

                                        this.$Modal.confirm({
                                            title: '提示',
                                            content: '<p>确认删除吗？</p>',
                                            onOk: () => {
                                                let postData = {
                                                    userId: params.row.id
                                                };

                                                this.util.post('/hand/deleteUser', postData, 'formdata').then(res => {
                                                    if(res.status == 200) {
                                                        this.$Message.success(res.msg);
                                                        this.getDetail();
                                                    } else {
                                                        this.$Message.warning(res.msg)
                                                    }
                                                })
                                            },
                                        });
                                    }
                                }
                            }, '删除');
                            let reset = h('a', {
                                class: 'green m-r-10',
                                on: {
                                    click: () => {
                                        console.log('删除', params.row);

                                        this.$Modal.confirm({
                                            title: '提示',
                                            content: '<p>重置后密码为：123456</p>',
                                            onOk: () => {
                                                let postData = {
                                                    userId: params.row.id
                                                };

                                                this.util.post('/hand/resetPwd', postData, 'formdata').then(res => {
                                                    if(res.status == 200) {
                                                        this.$Message.success(res.msg);
                                                        this.getDetail();
                                                    } else {
                                                        this.$Message.warning(res.msg)
                                                    }
                                                })
                                            },
                                        });
                                    }
                                }
                            }, '重置密码');
                            return h('div', [edit, del, reset]);
                        }
                    },
                ],

            }
        },
        created() {
            // this.getList();
            this.getRoleList();
            this.getOrList();
        },
        mounted() {
            let mainContent = document.getElementById('mainContent')
            if(mainContent) {
                this.tableHeight =  mainContent.offsetHeight - 40
            }
            this.timer = setInterval(() => {
                if(mainContent) {
                    this.tableHeight =  mainContent.offsetHeight - 40
                } else {
                    mainContent = document.getElementById('mainContent')
                }
            }, 1000)
        },
        beforeDestroy() {
            clearInterval(this.timer);
        },
        methods: {

            getRoleList() {

                let postData = {

                };
                this.util.get('/hand/roleInf', postData).then(res => {
                    console.log('获取列表', JSON.parse(JSON.stringify(res)))
                    this.roleList = res.data || [];

                })
            },
            getOrList() {

                let postData = {
                    pageSize: this.pageSize,
                    pageNum: this.page,
                    // orName: this.search.str,
                };
                this.util.get('/hand/orLists', postData).then(res => {
                    console.log('获取列表', JSON.parse(JSON.stringify(res)))
                    if(res.data) {
                        res.data.forEach(v => {
                            v.expand = true
                            v.children && v.children.forEach(val => val.expand = true);
                        })

                    }
                    this.list = res.data || [];
                    if(!this.detailId && this.list.length) {
                        this.detailId = this.list[0].id
                        this.getDetail()
                    } else {
                        this.getDetail()
                    }

                })
            },
            changeSelect(item) {
                console.log('所选机构', JSON.parse(JSON.stringify(item)));
                // this.detail = item[0] || '';
                if(item[0]) {
                    this.detailId = item[0].id;
                    this.getDetail()
                }



            },
            getDetail() {

                let postData = {
                    orId: this.detailId,
                };
                this.util.get('/hand/orInf', postData).then(res => {
                    console.log('获取详情', JSON.parse(JSON.stringify(res)))
                    this.detail = res.data || {};
                })
                this.util.get('/hand/userAccountLists', postData).then(res => {
                    console.log('获取机构人员', JSON.parse(JSON.stringify(res)))
                    res.data && res.data.forEach(v => {
                        v.state = v.status === 'T'
                    })
                    this.userList = res.data || []
                })

            },

            changeStatus(item) {
                console.log('item', item);
                let postData = {
                    id: item.id,
                    status: item.state ? 'T': 'F'
                };

                let url = '/hand/editUser';

                this.util.post(url, postData).then(res => {
                    if(res.status == 200) {
                        this.$Message.success(res.msg);
                        this.getDetail();
                    } else {
                        this.$Message.warning(res.msg)
                    }
                })
            },

            renderContent (h, { root, node, data }) {
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%'
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: 'ios-paper-outline'
                            },
                            style: {
                                marginRight: '8px'
                            }
                        }),
                        h('span', data.name)
                    ]),
                    h('span', {
                        style: {
                            display: 'inline-block',
                            float: 'right',
                            marginRight: '32px'
                        }
                    }, [
                        h('Button', {
                            props: {
                                icon: 'ios-add',
                                size: 'small'
                            },
                            style: {
                                marginLeft: '8px',
                                marginRight: '8px'
                            },
                            on: {
                                click: () => { this.addChild(data) }
                            }
                        }),
                        // h('Button', {
                        //     props: {
                        //         icon: 'ios-create-outline',
                        //         size: 'small'
                        //     },
                        //     style: {
                        //         marginRight: '8px'
                        //     },
                        //     on: {
                        //         click: () => { this.editItem(data) }
                        //     }
                        // }),
                        // h('Button', {
                        //     props: {
                        //         icon: 'ios-remove',
                        //         size: 'small'
                        //     },
                        //     on: {
                        //         click: () => { this.removeItem(root, node, data) }
                        //     }
                        // })
                    ])
                ]);
            },
            sortChange(e) {
                console.log('sort', e)
            },
            onPageChange(page) {
                this.page = page;
                this.getList();
            },
            //改变每页条数
            changePageSize(size) {
                this.pageSize = size;
                this.onPageChange(1)
            },
            goSearch() {
                this.onPageChange(1)
            },
            reset() {
                this.search = {
                    str: '',
                };
                this.goSearch();
            },
            getList() {
                let postData = {
                    pageSize: this.pageSize,
                    pageNum: this.page,
                    orName: this.search.str,
                };
                this.util.get('/management/orgnizationLists', postData).then(res => {
                    console.log('获取列表', JSON.parse(JSON.stringify(res)))
                    this.list = res.data || [];
                    this.total = res.total || 0;

                })
            },

            addItem() {
                this.itemModal = true;
                this.itemData = {
                    "orgnization_id": this.detail.id,
                    "role_id": itemData.role_id,
                    "role_name": role.name,
                    "user_account": itemData.user_account,
                    "user_name": itemData.user_name,
                };
            },
            addChild(item) {
                console.log('item', item);

                this.itemModal = true;
                this.itemData = {
                    "or_name": "",
                    "contact_person": "",
                    "contact_phone": "",
                };
            },
            editItem(item) {
                console.log('item', item);

                this.itemModal = true;
                this.itemData = {
                    id: item.id,
                    "role_id": item.role_id,
                    "user_account": item.user_account,
                    "user_name": item.user_name,
                };
            },
            removeItem(root, node, data) {
                console.log('root', root);
                console.log('node', node);
                console.log('data', data);


                // const parentKey = root.find(el => el === node).parent;
                // const parent = root.find(el => el.nodeKey === parentKey).node;
                // const index = parent.children.indexOf(data);
                // parent.children.splice(index, 1);
            },

            confirm() {
                let itemData = this.itemData;

                if(!itemData.user_account) {
                    this.$Message.warning('请输入账号');
                    return;
                }
                if(!itemData.user_name) {
                    this.$Message.warning('请输入真用户名称');
                    return;
                }

                if(!itemData.role_id) {
                    this.$Message.warning('请选择用户角色');
                    return;
                }

                let role = this.roleList.find(v => v.id == itemData.role_id)

                if(!role) {
                    this.$Message.warning('请选择用户角色');
                    return;
                }


                let postData = {
                    "orgnization_id": this.detail.id,
                    "role_id": itemData.role_id,
                    "role_name": role.name,
                    "user_account": itemData.user_account,
                    "user_name": itemData.user_name,
                };

                let url = '/hand/createUserInf';
                if(itemData.id) {
                    postData.id = itemData.id;
                    url = '/hand/editUser';
                }

                this.util.post(url, postData).then(res => {
                    if(res.status == 200) {
                        this.$Message.success(res.msg);
                        this.getDetail();
                        this.itemModal = false;
                    } else {
                        this.$Message.warning(res.msg)
                    }
                })

            },
        },
    }
</script>

